package com.example.mybatisplus.web.controller;

import java.util.List;
import java.io.InputStream;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.mybatisplus.model.dto.PageDTO;
import com.example.mybatisplus.service.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.example.mybatisplus.common.JsonResponse;
import com.example.mybatisplus.common.utls.JsonXMLUtils;
import com.example.mybatisplus.common.utls.SessionUtils;
import com.example.mybatisplus.mapper.ConRecordMapper;
import com.example.mybatisplus.model.domain.ConRecord;
import com.example.mybatisplus.model.domain.ConRecordDetail;
import com.example.mybatisplus.model.domain.ConWorkAnalyze;
import com.example.mybatisplus.model.domain.ConditionedConReport;
import com.example.mybatisplus.model.domain.FirstApoStatus;
import com.example.mybatisplus.model.domain.StuInfo;
import com.example.mybatisplus.model.domain.UserAccount;
import com.example.mybatisplus.service.ConRecordService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;


import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

import javax.servlet.http.HttpServletResponse;

/**
 *
 *  前端控制器
 *
 *
 * @author cft
 * @since 2022-06-24
 * @version v1.0
 */
@Controller
@RequestMapping("/api/conRecord")
public class ConRecordController {

    private final Logger logger = LoggerFactory.getLogger( ConRecordController.class );

    @Autowired
    private ConRecordService conRecordService;

    @Autowired
    private MailService mailService;

    /**
    * 描述：根据Id 查询
    *
    */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getById(@PathVariable("id") Long id)throws Exception {
        ConRecord  conRecord =  conRecordService.getById(id);
        return JsonResponse.success(conRecord);
    }

    /**
    * 描述：根据Id删除
    *
    */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public JsonResponse deleteById(@PathVariable("id") Long id) throws Exception {
        conRecordService.removeById(id);
        return JsonResponse.success(null);
    }


    /**
    * 描述：根据Id 更新
    *
    */
    @RequestMapping(value = "", method = RequestMethod.PUT)
    @ResponseBody
    public JsonResponse updateConRecord(ConRecord  conRecord) throws Exception {
        conRecordService.updateById(conRecord);
        return JsonResponse.success(null);
    }


    /**
    * 描述:创建ConRecord
    *
    */
    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse create(ConRecord  conRecord) throws Exception {
        conRecordService.save(conRecord);
        return JsonResponse.success(null);
    }

    /*
    * author:tqq
    * 安排学生咨询，安排时间地点老师
    * 根据初访结果 安排
    * ConRecord conRecord, FirstApoStatus firstApoStatus, UserAccount user
    * */
    @RequestMapping ("/arrangCon")
    @ResponseBody
    public JsonResponse arrangCon(@RequestBody Map<String, Object> models){
        ConRecord conRecord= null;
        try {
            conRecord = JsonXMLUtils.map2object((Map<String, Object>)models.get("conRecord"), ConRecord.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        FirstApoStatus firstApoStatus= null;
        try {
            firstApoStatus = JsonXMLUtils.map2object((Map<String, Object>)models.get("firstApoStatus"), FirstApoStatus.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        UserAccount user= null;
        try {
            user = JsonXMLUtils.map2object((Map<String, Object>)models.get("user"), UserAccount.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        conRecordService.arrangConForStu(conRecord,firstApoStatus, user);
        return JsonResponse.success("安排成功");
    }

    /*
    * author:tqq
    * 实现咨询助理查看已经安排的咨询
    * */
    @RequestMapping("/disArranged")
    @ResponseBody
	public JsonResponse disArranged(PageDTO pageDTO) {
		Page<ConRecord> page = conRecordService.displayArranged(pageDTO);
		return JsonResponse.success(page);
	}


	/*
	 * author:cft
	 * function:咨询师查看所有安排好的咨询和对应的学生信息以及学生的初访信息，包括问卷填写情况
	 */
	@Autowired
	ConRecordMapper conRecordMapper;

	@RequestMapping("/getConRecordDetail")
	@ResponseBody
	public JsonResponse getConRecordDetail(PageDTO pageDTO, StuInfo stu, UserAccount con,
			FirstApoStatus firstApoStatus) {
		PageHelper.startPage(pageDTO.getPageNo(), pageDTO.getPageSize());
		con.setUserId(SessionUtils.getCurrentUserInfo().getUserId());//获得咨询师id
		List<ConRecordDetail> list = conRecordMapper.getConRecordDetail(stu, con, firstApoStatus);
		PageInfo<ConRecordDetail> pageInfo = new PageInfo<>(list);
		return JsonResponse.success(pageInfo);
	}

	/*
	 * author:cft
	 * function:查询老师下某个学生的所有咨询记录
	 */
	@RequestMapping("/getStuConDetail")
	@ResponseBody
	public JsonResponse getStuConDetail(@RequestBody JSONObject jsonObject) {
		Long stuId = Long.parseLong(jsonObject.getString("conStuId"));
		Long conId = Long.parseLong(jsonObject.getString("conTeacherId"));
		List<ConRecord> list = conRecordService.getStuConDetail(stuId, conId);
		return JsonResponse.success(list);
	}



	/*
	 * author:cft
	 * function:当学生第一次咨询时,调用此接口,更新数据库中的记录
	 */
	@RequestMapping("/updateConRecord")
	@ResponseBody
	public JsonResponse updateStuConRecord(@RequestBody ConRecord conRecord) {
		conRecordService.updateById(conRecord);
		return JsonResponse.success("success");
	}
	/*
	 * author:cft
	 * function:添加咨询记录
	 */
	@RequestMapping("/insertNewConRecord")
	@ResponseBody
	public JsonResponse insertNewConRecord(@RequestBody ConRecord conRecord) {
		conRecordService.setNewConRecordTimes(conRecord);
		return JsonResponse.success("success");
	}





    /*
     * author:tqq
     * 实现咨询助理发邮件通知学生
     * */
    @RequestMapping("/sendEmail")
    @ResponseBody
	public JsonResponse sendEmail(@RequestBody JSONObject json) {
		//System.out.println("json为："+json);
		String to = json.getString("to");
		String subject = json.getString("subject");
		String content = json.getString("content");
		mailService.sendSimpleMail(to, subject, content);
		return JsonResponse.success(null, "已发送");
	}


	/*
	 * author:cft
	 * function:得到所有待审核的追加咨询申请
	 */
	@RequestMapping("/getExtraConApo")
	@ResponseBody
	public JsonResponse getExtraConApo(@RequestBody JSONObject jsonObject) {
		PageDTO pageDTO=new PageDTO();
		pageDTO.setPageNo(Integer.parseInt(jsonObject.getString("pageNo")));
		pageDTO.setPageSize(Integer.parseInt(jsonObject.getString("pageSize")));
		UserAccount con = new UserAccount();
		if(jsonObject.getString("userId")!="")
			con.setUserId(Long.parseLong(jsonObject.getString("userId")));
		if (jsonObject.getString("name") != "")
			con.setName(jsonObject.getString("name"));
		PageHelper.startPage(pageDTO.getPageNo(), pageDTO.getPageSize());
		List<ConRecordDetail> list = conRecordMapper.getExtraConApo(con);
		PageInfo<ConRecordDetail> pageInfo = new PageInfo<>(list);
		return JsonResponse.success(pageInfo);
	}


	/*
	 * author:cft
	 * function:得到咨询师工作情况的统计信息
	 */
	@RequestMapping("/getConWorkInfo")
	@ResponseBody
	public JsonResponse getConWorkInfo(@RequestBody JSONObject jsonObject) {
		PageDTO pageDTO=new PageDTO();
		pageDTO.setPageNo(Integer.parseInt(jsonObject.getString("pageNo")));
		pageDTO.setPageSize(Integer.parseInt(jsonObject.getString("pageSize")));
		UserAccount con = new UserAccount();
		if(jsonObject.getString("userId")!="")
			con.setUserId(Long.parseLong(jsonObject.getString("userId")));
		if (jsonObject.getString("name") != "")
			con.setName(jsonObject.getString("name"));
		PageHelper.startPage(pageDTO.getPageNo(), pageDTO.getPageSize());
		List<ConWorkAnalyze> list= conRecordMapper.getConWorkInfo(con);
		PageInfo<ConWorkAnalyze> pageInfo = new PageInfo<>(list);
		return JsonResponse.success(pageInfo);
	}


    /*
    * author:tqq
    * 查询所有的结案报告
    * */
    @RequestMapping("/disEndReport")
    @ResponseBody
    public JsonResponse disEndReport(PageDTO pageDTO){
        Page<ConRecord> page = conRecordService.displayEnd(pageDTO);
        return JsonResponse.success(page);
    }

    /*
     * author:tqq
     * 导出所有的结案报告
     * */
    @PostMapping("/exportEndcon")
    @ResponseBody
	public void exportEndcon(HttpServletResponse httpServletResponse) {
		conRecordService.exportEndcon(httpServletResponse);
	}

	/*
	 * author:cft
	 * function:根据条件查询对应的结案报告
	 */
	@RequestMapping("/getConditionedConReport")
	@ResponseBody
	public JsonResponse getConditionedConReport(@RequestBody JSONObject jsonObject) {
		PageDTO pageDTO=new PageDTO();
		pageDTO.setPageNo(Integer.parseInt(jsonObject.getString("pageNo")));
		pageDTO.setPageSize(Integer.parseInt(jsonObject.getString("pageSize")));
		System.out.println(jsonObject);
		String stuId=jsonObject.getString("stuId");
		String stuName=jsonObject.getString("stuName");
		String teacherId=jsonObject.getString("teacherId");
		String teacherName=jsonObject.getString("teacherName");
		String topic=jsonObject.getString("topic");
		List<ConditionedConReport> list = conRecordMapper.getConditionedConReport(stuId, stuName, teacherId,
				teacherName, topic);
		PageInfo<ConditionedConReport> pageInfo = new PageInfo<>(list);
		return JsonResponse.success(pageInfo);

	}

    /*
     * author:tqq
     * 查询当前咨询师的所有结案报告
     * */
    @RequestMapping("/dismyEndReport")
    @ResponseBody
    public JsonResponse dismyEndReport(PageDTO pageDTO){
        Page<ConRecord> page = conRecordService.displaymyEnd(pageDTO);
        return JsonResponse.success(page);
    }

	/*
	 * author:tqq
	 * 导出咨询师工作统计
	 * */
	@PostMapping("/exportConwork")
	@ResponseBody
	public void exportConwork (HttpServletResponse httpServletResponse,@RequestBody JSONObject[] json){
		conRecordService.exportConwork(httpServletResponse,json);
	}
}

